import requests
import websocket
import json


def get_room_id(room_url):
    response = requests.get(room_url)
    room_id = response.text.split('"room_id":')[1].split(',')[0]
    return room_id


def connect_danmu_server(room_id):
    url = 'wss://danmuproxy.douyu.com:8506/'
    ws = websocket.create_connection(url)
    msg = 'type@=loginreq/roomid@={}/\0'.format(room_id)
    ws.send(msg.encode('utf-8'))
    msg = 'type@=joingroup/rid@={}/gid@=-9999/\0'.format(room_id)
    ws.send(msg.encode('utf-8'))
    return ws


def parse_danmu_message(ws):
    while True:
        try:
            message = ws.recv()
            if message:
                message = message.decode('utf-8', 'ignore')
                if 'type@=' in message:
                    msg_type = message.split('type@=')[1].split('/')[0]
                    if msg_type == 'chatmsg':
                        content = message.split('txt@=')[1].split('/')[0]
                        print(content)
        except Exception as e:
            print(e)


# 示例用法（验证未成功）
if __name__ == '__main__':
    room_url = 'https://www.douyu.com/room/479079'  # 替换成你要爬取的房间链接
    room_id = get_room_id(room_url)
    ws = connect_danmu_server(room_id)
    parse_danmu_message(ws)
